package com.kai.steering.common.web.ctl;

import com.kai.steering.common.vo.CommonConstant;
import com.kai.steering.common.vo.Result;
import com.kai.steering.common.vo.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ Author     ：LiuKai.
 * @ Date       ：Created in 10:48 2022-2-22
 * @ Description：通用请求
 * @ Modified By：
 * @Version:
 */
@Slf4j
public abstract class BaseController {

    /**
     * 获取当前请求
     *
     * @return request
     */
    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取当前请求
     *
     * @return response
     */
    public HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }


    /**
     * 获取当前用户
     *
     * @return response
     */
    public String getUser() {
        return getRequest().getAttribute(CommonConstant.HEAD_USER_ID).toString();
    }


    /**
     * <p>
     * 请求成功
     * </p>
     *
     * @param data 数据内容
     * @param <T>  对象泛型
     * @return
     */
    protected <T> Result<T> ok(T data) {
        return Result.ok(data);
    }

    /**
     * <p>
     * 请求失败
     * </p>
     *
     * @param msg 提示内容
     * @return
     */
    protected Result<Object> fail(String msg) {
        return Result.failed(msg);
    }

    /**
     * <p>
     * 请求失败
     * </p>
     *
     * @param apiCode 请求错误码
     * @return
     */
    protected Result<Object> fail(ReturnCode apiCode) {
        return Result.failed(apiCode);
    }
}